package com.zswl.bus;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.zswl.bus.SelectPhotoDialog.REQUEST_CODE_CAMERA;
import static com.zswl.bus.SelectPhotoDialog.REQUEST_CODE_LOCAL;

/**
 * Created by cenxiaozhong on 2017/5/26.
 * <p>
 * source code  https://github.com/Justson/AgentWeb
 */

public abstract class BaseWebActivity extends AppCompatActivity {


    protected AgentWeb mAgentWeb;
    private LinearLayout mLinearLayout;
    //    private Toolbar mToolbar;
//    private TextView mTitleTextView;
    private AlertDialog mAlertDialog;
    protected Context context;
    private String uploadImgPath;
    private String takePhotoPath;
    protected String myId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_web);
        context = this;

        mLinearLayout = (LinearLayout) this.findViewById(R.id.container);
//        mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
//        mToolbar.setTitleTextColor(Color.WHITE);
//        mToolbar.setTitle("");
//        mTitleTextView = (TextView) this.findViewById(R.id.toolbar_title);
//        this.setSupportActionBar(mToolbar);
//        if (getSupportActionBar() != null) {
//            // Enable the Up button
//            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        }
//        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                showDialog();
//            }
//        });


        long p = System.currentTimeMillis();

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(getUrl());

        //mAgentWeb.getUrlLoader().loadUrl(getUrl());

        long n = System.currentTimeMillis();
        Log.i("Info", "init used time:" + (n - p));


    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
//            Log.i("Info","onProgress:"+newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            if (mTitleTextView != null) {
//                mTitleTextView.setText(title);
//            }
        }
    };

    public abstract String getUrl();


    private void showDialog() {

        if (mAlertDialog == null) {
            mAlertDialog = new AlertDialog.Builder(this)
                    .setMessage("您确定要关闭该页面吗?")
                    .setNegativeButton("再逛逛", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mAlertDialog != null) {
                                mAlertDialog.dismiss();
                            }
                        }
                    })//
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            if (mAlertDialog != null) {
                                mAlertDialog.dismiss();
                            }
                            BaseWebActivity.this.finish();
                        }
                    }).create();
        }
        mAlertDialog.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
//        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    /**
     * 上传头像
     *
     * @param path
     */
    protected void updateHeadrImg(final String path) {

        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                uploadImgPath = ImageUtil.getimage(path);//先进行压缩
                if (!TextUtils.isEmpty(uploadImgPath)) {
                    emitter.onNext(true);
                } else {
                    emitter.onNext(false);
                }
                emitter.onComplete();
            }
        }).flatMap(new Function<Boolean, ObservableSource<String>>() {
            @Override
            public ObservableSource<String> apply(Boolean aBoolean) throws Exception {
                final RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), new File(uploadImgPath));
                MultipartBody.Part part = MultipartBody.Part.createFormData("header", "android" + System.currentTimeMillis() + ".jpg", requestBody);
                return ApiService.getInstance().getApi().uploadHeadImg(part);
            }
        }).compose(RxUtil.io_main_nolife())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String result) {
                        Log.d(TAG, "onNext: " + result);
                        try {
                            JSONObject object = new JSONObject(result);
                            String msg = object.getString("msg");
                            String code = object.getString("code");
                            if ("0".equals(code)) {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                return;
                            }
                            String data = object.getString("data");
//                            mAgentWeb.getJsAccessEntrace().quickCallJs("getDriver",myId,data);
                            String js = "javascript:getDriver('%s,%s')";
                            mAgentWeb.getWebCreator().getWebView().loadUrl(String.format(js, myId, data));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        String js = "javascript:getDriver('%s,%s')";
//                        String js = "getDriver('%s,%s')";
//                        mAgentWeb.getWebCreator().getWebView().loadUrl());
//                        mAgentWeb.getJsAccessEntrace().quickCallJs("getDriver",myId,result.getData().toString());
//                        webView.loadUrl(String.format(js, myId, result));
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onNext: " + e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private static final String TAG = "BaseWebActivity";

    @Override
    protected void onResume() {
//        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.i("Info", "onResult:" + requestCode + " onResult:" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                updateHeadrImg(takePhotoPath);
            } else if (requestCode == REQUEST_CODE_LOCAL) { // send local image
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            }
        }
    }

    /**
     * 选择头像
     */
    public void changeHeaderImg() {
        RxPermissions permissions = new RxPermissions(this);
        // Must be done during an initialization phase like onCreate
        permissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            SelectPhotoDialog dialog = new SelectPhotoDialog(context);
                            dialog.setListener(new SelectPhotoDialog.SelectListener() {
                                @Override
                                public void photo(String path) {
                                    takePhotoPath = path;
                                }
                            });
                            dialog.show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(context, "请打开相机权限", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * send image
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast.makeText(context, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            updateHeadrImg(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast.makeText(context, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            updateHeadrImg(file.getAbsolutePath());

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
//        mAgentWeb.getWebLifeCycle().onDestroy();
    }
}
